<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once ('./application/controllers/authenticate.php');
class Article extends Authenticate {
	
	const MANGA_PAGE_RANGE = 5;
	const MANGA_PER_PAGE = 20;
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('cms_article_model');
		$this->load->model('cms_category_model');
		$this->load->library('html/control/fx_control');
		$this->load->library('html/control/fx_filter');
		$this->load->library('html/control/fx_sort');
		$this->cms_article_model->addAttributeOrder('id', 'desc');
		$this->load->library('upload');
		// Load Article Model
		$this->loadCurrentArticle();
	}

	public function loadCurrentArticle() 
	{
		try {
			// Load Article Model
			$id = $this->input->getParam('id');
			if ($id) {
				$this->cms_article_model->loadByPK($id);
				$this->st_registry->register('admin/cms/article/id', $id);
			} else {
				if ($id = $this->st_registry->registry('admin/cms/article/id'))
				{
					$this->cms_article_model->loadByPK($id);
				}
			}
			return $this->cms_article_model;
		} catch (Exception $ex) {
			return null;
		}
	}
	public function index() 
	{	
		try {
			//Unload Current Article
			$this->st_registry->clearRegistry('admin/cms/article/id');
			//Get Data
			$data = $this->_initGridView();
			//Transfer To View
			$this->load->view('cms/article', $data);
		} catch (Exception $ex) {
			echo $ex->getMessage();
		}
	}
	
	public function edit() 
	{
		try {
			$data = $this->_initGridView();
			$data['categories'] = $this->cms_category_model->getCollection();
			$this->load->view('cms/article/edit', $data);	
		} catch (Exception $ex) {
			echo $ex->getMessage();
		}
	}
	
	protected function _initGridView()
	{
		$this->cms_article_model->resetFilterList();
		// Get Paginator Params
		$page = $this->input->getParam('page');
		$recordPerPage = $this->input->getParam('recordPerPage');
		if (!$recordPerPage) {
			$recordPerPage = self::MANGA_PER_PAGE;
		}
		// Get Filter Params	
		$filters = $this->input->post('articleFilter');
		// Filter
		$this->fx_filter->filter($filters, $this->cms_article_model);
		// Get Order Params
		$order = $this->input->post('articleOrder');
		// Sort
		$this->fx_sort->sort($order, $this->cms_article_model);
		// Get total found records
		$found = $this->cms_article_model->countTotal();
		// Paginate
		$this->load->library("tree/paginator/engine/st_paginator_collection");
		$this->load->library("tree/paginator/st_paginator");
		$this->st_paginator_collection->setModel($this->cms_article_model);
		$this->st_paginator->setConfig(array(
			'engine' => $this->st_paginator_collection,
			'pageRange' => self::MANGA_PAGE_RANGE,
			'itemCountPerPage' => $recordPerPage,
			'currentPageNumber' => $page  
		));		
		// Paginate Collection
		$collection = $this->st_paginator->getItemsByPage($page);
		if (empty($collection)) {
			$collection = array();
		}
		$data = array();
		$data['article_selected'] = $this->input->post('article_selected');
		$data['found'] = $found;
		$data['article_ids'] = $this->input->post('article_ids');
		$data['category_id'] = $this->input->post('category_id');
		$data['article_ids_array'] = explode(',', $this->input->post('article_ids'));
		
		/*END RADIO SELECTED*/
		//echo $data['article_ids'];
		$data['model'] = $this->cms_article_model;
		$data['sorter'] = $this->fx_sort;
		$data['filters'] = $this->fx_filter;
		$data['paginator'] = $this->st_paginator;
		$data['collection'] = $collection;
		return $data;
	}
	
	public function publish()
	{
		try {
			// Load Article Model
			$ids = $this->input->getMassValues('article_ids');
			$publishDay = $this->input->post('publishDay');
			if ($ids) {
				$this->cms_article_model->query("update cms_article set is_publish = 1, publish_day = \"$publishDay\" where id in ($ids)");
			}
			$countItem = count(explode(',', $ids));
			$this->st_registry->register('admin/cms/article/message', "Publish $countItem items successfully");
			redirect(site_url("admin/cms/article/index", true));
		} catch (Exception $ex) {
			$this->st_registry->register('admin/cms/article/message', $e->getMessage());
			redirect(site_url("admin/cms/article/index", true));
		}
	}
	
	public function unpublish()
	{
		try {
			// Load Article Model
			$ids = $this->input->getMassValues('article_ids');
			if ($ids) {
				$this->cms_article_model->query("update cms_article set is_publish = 0 where id in ($ids)");
			}
			$countItem = count(explode(',', $ids));
			$this->st_registry->register('admin/cms/article/message', "Unpublish $countItem items successfully");
			redirect(site_url("admin/cms/article/index", true));
		} catch (Exception $ex) {
			$this->st_registry->register('admin/cms/article/message', $e->getMessage());
			redirect(site_url("admin/cms/article/index", true));
		}
	}
	
	public function setCategory()
	{
		try {
			// Load Article Model
			$ids = $this->input->getMassValues('article_ids');
			$categoryId = $this->input->post('categorySetterId');
			if ($ids && (integer)$categoryId != 0) {
				$this->cms_article_model->query("update cms_article set category_id = $categoryId where id in ($ids)");
			}
			$countItem = count(explode(',', $ids));
			$this->st_registry->register('admin/cms/article/message', "Update $countItem items successfully");
			redirect(site_url("admin/cms/article/index", true));
		} catch (Exception $ex) {
			$this->st_registry->register('admin/cms/article/message', $e->getMessage());
			redirect(site_url("admin/cms/chapter/index", true));
		}
	}
	 
	public function save() 
	{
		try {
			//print_r ($this->input->post('article'));
			// Load Article Model
			$id = $this->input->post('id');
			if ($id) {
				$this->cms_article_model->loadByPK($id);
			} else {
				$this->cms_article_model->setCreatedAt("NOW()");
			}
			$data = $this->input->post('article');
			if (is_array($data) && count($data) > 0) {
				$this->cms_article_model->setEntireData($data);
				
				//Upload Thumb Image
				$config['upload_path'] = './media/cms/article/thumbs/';
				$config['allowed_types'] = 'gif|jpg|png|bmp';
				$config['max_size']	= '500';
				
				$this->upload->initialize($config);
				$this->upload->do_upload('article_thumb');
				$dataUpload = $this->upload->data();
				$thumbPath = $config['upload_path'].$dataUpload['file_name'];
				if (strlen($dataUpload['file_name']) > 0) {
					$this->cms_article_model->setThumbImage($thumbPath);
				}
				
				//Upload Cover Image
				$config['upload_path'] = './media/cms/article/images/';
				$this->upload->initialize($config);
				$this->upload->do_upload('article_image');
				$dataUpload = $this->upload->data();
				$imagePath = $config['upload_path'].$dataUpload['file_name'];
				if (strlen($dataUpload['file_name']) > 0) {
					$this->cms_article_model->setMainImage($imagePath);
				}

				$this->cms_article_model->setUpdatedAt("NOW()");
				$this->cms_article_model->save();
			}
			redirect(site_url("admin/cms/article/edit/id/".$this->cms_article_model->getId(), true));
		} catch (Exception $ex) {
			echo $ex->getMessage();
		}
	}
	
	public function delete()
	{
		try {
			if ($this->cms_article_model->isLoaded()) {
				$name = $this->cms_article_model->getTitle();
				$this->cms_article_model->delete();
				$this->st_registry->register('admin/cms/article/message', "Delete article $name successfully");
				redirect(site_url("admin/cms/article/index", true));
			}
			else {
				$this->st_registry->register('admin/cms/article/message', "Cannot delete article");
				redirect(site_url("admin/cms/article/index", true));
			}
		} catch (Exception $ex) {
			$this->st_registry->register('admin/cms/article/message', "Error when deleting article");
			redirect(site_url("admin/cms/article/index", true));
		}
	}
	
	public function generalTab()
	{
		//Get Data
		$data = $this->_initGridView();
		$data['categories'] = $this->cms_category_model->getCollection();
		$this->load->view('cms/article/edit/form', $data);
	}
	
	public function publishTab()
	{
		//Get Data
		$data = $this->_initGridView();
		$this->load->view('cms/article/edit/publish', $data);
	}
	
	public function metaTab() 
	{
		//Get Data
		$data = $this->_initGridView();
		$this->load->view('cms/article/edit/meta', $data);
	}
}